package com.zqcy.workbench.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ClientRequestException;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.ocr.v1.OcrClient;
import com.huaweicloud.sdk.ocr.v1.model.BankcardRequestBody;
import com.huaweicloud.sdk.ocr.v1.model.BankcardResult;
import com.huaweicloud.sdk.ocr.v1.model.RecognizeBankcardRequest;
import com.huaweicloud.sdk.ocr.v1.model.RecognizeBankcardResponse;
import com.huaweicloud.sdk.ocr.v1.region.OcrRegion;
import com.onemdos.base.OneMDOSContext;
import com.onemdos.base.permisson.BasePermission;
import com.onemdos.base.permisson.PermissionCallback;
import com.shinemo.base.core.utils.FileUtil;
import com.shinemo.base.core.utils.Handlers;
import com.shinemo.base.core.utils.PermissionUtils;
import com.shinemo.component.thread.task.AsyncTask;
import com.zqcy.workbench.R;
import com.onemods.safekeyboard.SafeKeyboard;
import com.zqcy.workbench.utils.KeyboardUtils;
import com.zqcy.workbench.utils.MyTextWatcher;
import com.zqcy.workbench.utils.TransferDialog;
import com.zqcy.workbench.utils.Utils;

import java.io.File;
import java.io.IOException;

import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.MANAGE_EXTERNAL_STORAGE;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static com.shinemo.base.core.utils.Keys.MANAGE_ALL_FILES;
import static com.zqcy.workbench.utils.Constants.REQUEST_CODE_TAKE_PICTURE_BANK;
import static com.zqcy.workbench.utils.Constants.REQUEST_CODE_TAKE_PICTURE_ID;

/**
 * 转账页面
 */
public class TransferActivity extends AppCompatActivity {

    private SafeKeyboard safeKeyboard;
    private LinearLayout keyboardContainer;

    private LinearLayout transferLayout;
    private RelativeLayout transferRoot;

    private EditText transferMoney; //金额
    private EditText transferName; //户名
    private EditText transferAccount; //账号
    private ImageView transferAccountScan; //账号扫描
    private ImageView transferNameScan;//户名扫描

    private TextView transferBank;
    private TextView transferPayBank;
    private TextView transferPayMoney;

    private TextView transferContinue;
    private ImageView ivBack;

    private TransferDialog transferDialog;

    private Uri imageUri;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, TransferActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer);
        Utils.setColor(this, getResources().getColor(R.color.white));
        initView();
        initListener();

    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void initView() {
        transferBank = findViewById(R.id.transfer_bank);
        transferPayBank = findViewById(R.id.transfer_pay_bank);
        transferPayMoney = findViewById(R.id.transfer_pay_money);

        ivBack = findViewById(R.id.iv_back);
        transferMoney = findViewById(R.id.transfer_money);
        transferAccount = findViewById(R.id.transfer_account);
        transferName = findViewById(R.id.transfer_name);
        transferContinue = findViewById(R.id.transfer_continue);
        transferAccountScan = findViewById(R.id.transfer_account_scan);
        transferNameScan = findViewById(R.id.transfer_name_scan);

        transferRoot = findViewById(R.id.transfer_root);
        transferLayout = findViewById(R.id.transfer_layout);
        keyboardContainer = findViewById(R.id.keyboardPlace);

        safeKeyboard = new SafeKeyboard(OneMDOSContext.getInstance().getContext().getApplicationContext(), keyboardContainer,
                R.layout.mdos_keyboard_layout_keyboard_containor, R.id.safeKeyboardLetter, transferRoot, transferLayout);

        transferDialog = new TransferDialog(TransferActivity.this);

        /**
         * 默认 可自定义修改
         */
        safeKeyboard.setDelDrawableChange(getDrawable(R.drawable.mdos_keyboard_del_change))
                .setDelDrawable(getDrawable(R.drawable.mdos_keyboard_icon_del_black))
                .setLowDrawableChange(getDrawable(R.drawable.mdos_keyboard_low_change))
                .setLowDrawable(getDrawable(R.drawable.mdos_keyboard_icon_capital_selected_white))
                .setUpDrawableChange(getDrawable(R.drawable.mdos_keyboard_up_change))
                .setUpDrawable(getDrawable(R.drawable.mdos_keyboard_icon_capital_selected_black))
                .setUpDrawableLockChange(getDrawable(R.drawable.mdos_keyboard_uplock_change))
                .setUpDrawableLock(getDrawable(R.drawable.mdos_keyboard_icon_capital_selected_lock))
                .setSpecialDrawableChange(getDrawable(R.drawable.mdos_keyboard_special_change));

        safeKeyboard.putEditText(transferMoney);
        safeKeyboard.putEditText(transferAccount);

        transferName.addTextChangedListener(new MyTextWatcher() {
            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable editable) {
                changeContinue(0);
            }
        });
        transferAccount.addTextChangedListener(new MyTextWatcher() {
            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable editable) {
                changeContinue(1);
            }
        });
//        transferAccount.setKeyListener(new DigitsKeyListener() {
//
//            @Override
//            public int getInputType() {
//                return InputType.TYPE_TEXT_VARIATION_PASSWORD;
//            }
//
//            @Override
//            protected char[] getAcceptedChars() {
//                // 只允许大小写字母、数字
//                String a = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
//                return a.toCharArray();
//            }
//        });
        transferMoney.addTextChangedListener(new MyTextWatcher() {
            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable editable) {
                changeContinue(2);
            }
        });
    }

    /**
     * 调用系统相机
     *
     * @param type 1 身份证识别 2 银行卡识别
     */
    private void takePhoto(int type) {
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            permissions = new String[]{READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, MANAGE_EXTERNAL_STORAGE, CAMERA};
        } else {
            permissions = new String[]{READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, CAMERA};
        }
        new BasePermission(this).request(new PermissionCallback() {
            @Override
            public void onPermission(boolean granted) {
                if (!granted) {
                    PermissionUtils.testAllFiles(TransferActivity.this);
                } else {
                    final File DownloadDir = new File(getExternalFilesDir(null), "Scan_Download");
                    if (!DownloadDir.exists()) { //如果该文件夹不存在，则进行创建
                        DownloadDir.mkdirs();//创建文件夹
                    }
                    Utils.delAllFile(DownloadDir.getPath());
                    imageUri = FileUtil.PathToUri(getApplicationContext(), DownloadDir.getPath() + File.separator + "Scan_" + System.currentTimeMillis() + ".png");
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    //Android7.0添加临时权限标记
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    if (type == 1) {
                        startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE_ID);
                    } else {
                        startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE_BANK);
                    }
                }
            }
        }, permissions);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        switch (requestCode) {
            case MANAGE_ALL_FILES:
                if (Environment.isExternalStorageManager()) {
//                    Toast.makeText(this, "访问所有文件权限申请成功", Toast.LENGTH_SHORT).show();
                }
                break;
            case REQUEST_CODE_TAKE_PICTURE_ID:


                break;
            case REQUEST_CODE_TAKE_PICTURE_BANK:
                try {
                    String base64 = Utils.bitmapToBase64(Utils.getBitmapFormUri(this, imageUri));
                    AsyncTask.build(() -> {
                        String ak = "M4CQO1KLRJOZRMHWIQCU"; //华为云测试access key 开发者自行更换
                        String sk = "UZdlHQMYS8VCMD7CuvtX0MNhp1uVpXB6vauME16B";//华为云测试Secret key 开发者自行更换
                        ICredential auth = new BasicCredentials()
                                .withAk(ak).withSk(sk).withProjectId("0657e5ca6e000fb82f33c01ee89bd2f1");
                        OcrClient client = OcrClient.newBuilder()
                                .withCredential(auth)
                                .withRegion(OcrRegion.valueOf("cn-north-4"))
                                .build();
                        BankcardRequestBody body = new BankcardRequestBody();
                        body.setImage(base64);
                        RecognizeBankcardRequest request = new RecognizeBankcardRequest().withBody(body);
                        try {
                            RecognizeBankcardResponse response = client.recognizeBankcard(request);
                            BankcardResult result = response.getResult();
                            Handlers.postMain(() -> {
//                                Log.e("Transfer", JSON.toJSONString(result));
                                ScanBank(result);
                            });
                        } catch (ConnectionException | RequestTimeoutException | ServiceResponseException e) {
                            e.printStackTrace();
                        }
                    }).start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    /**
     * ocr能力调用后ui变化
     *
     * @param result
     */
    @SuppressLint("SetTextI18n")
    private void ScanBank(BankcardResult result) {
        transferAccount.setText(result.getCardNumber());
        transferBank.setText(result.getBankName());
        String bankNumber = result.getCardNumber();
        if (bankNumber.length() > 4) {
            bankNumber = bankNumber.substring(bankNumber.length() - 4);
            transferPayBank.setText(result.getBankName() + "(" + bankNumber + ")");
        }
    }


    /**
     * 户名/账号/金额 输入改变
     *
     * @param type 0 户名 1 账号 2 金额
     */
    private void changeContinue(int type) {
        switch (type) {
            case 0:
                break;
            case 1:
                //账号改变 银行清空
                transferBank.setText("");
                transferPayBank.setText("");
                break;
        }
        String Name = transferName.getText().toString();
        String Account = transferAccount.getText().toString();
        String Money = transferMoney.getText().toString();
        if (!TextUtils.isEmpty(Name) && !TextUtils.isEmpty(Account) && !TextUtils.isEmpty(Money)) {
            transferContinue.setEnabled(true);
            transferContinue.setBackgroundResource(R.drawable.shape_transfer_red_radius);
        } else {
            transferContinue.setEnabled(false);
            transferContinue.setBackgroundResource(R.drawable.shape_transfer_grey_radius);
        }
    }


    // 当点击返回键时, 如果软键盘正在显示, 则隐藏软键盘并是此次返回无效
    @Override
    public void onBackPressed() {
        if (safeKeyboard.stillNeedOptManually(false)) {
            safeKeyboard.hideKeyboard();
            return;
        }
        super.onBackPressed();
    }

    private void initListener() {
        transferNameScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        transferAccountScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (safeKeyboard.stillNeedOptManually(false)) {
                    safeKeyboard.hideKeyboard();
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        takePhoto(2);
                    }
                }, 200);
            }
        });
        ivBack.setOnClickListener(view -> {
            if (safeKeyboard.stillNeedOptManually(false)) {
                safeKeyboard.hideKeyboard();
            }
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 200);
        });
        transferContinue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (safeKeyboard.stillNeedOptManually(false)) {
                    safeKeyboard.hideKeyboard();
                }
                String Money = transferMoney.getText().toString();
                transferDialog.setMoney(Money);
                if (!isFinishing()) {
                    transferDialog.show();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (safeKeyboard != null) {
            safeKeyboard.release();
            safeKeyboard = null;
        }
        super.onDestroy();
    }

    /**
     * 空白隐藏软键盘
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //获取当前获得焦点的View
                View view = getCurrentFocus();
                //调用方法判断是否需要隐藏键盘
                KeyboardUtils.hideKeyboard(ev, view, this);
                break;
        }
        return super.dispatchTouchEvent(ev);
    }


}